// 引入 Request
import Request from 'luch-request'
import md5 from 'js-md5'
import Config from '../config.js'
// #ifdef MP
import Auth from './auth.js'
// #endif

const network = new Request()

const _appKey = Config.APPKEY
const _appSecret = Config.APPSECRET

function _sign(method, params, kAppKey, kAppSecret) {
	if (method === 'POST') {
		const jsonStr = JSON.stringify(params)
		params = md5(jsonStr)
		params += '&appKey=' + kAppKey
	} else {
		if (typeof params === 'object') {
			var arr = []
			for (var key in params) {
				arr.push((key + '=' + params[key]))
			}
			arr.push('appKey=' + kAppKey)
			params = arr.join('&')
		} else if (typeof params === 'string') {
			params += '&appKey=' + kAppKey
		}
	}
	const urlStr = params.split('&').sort().reverse().join('&')
	return md5(decodeURIComponent(urlStr) + '&s=' + kAppSecret)
}

/* config 为默认全局配置*/
network.setConfig((config) => {
	/* 根域名 */
	config.baseURL = Config.MODE == 'dev' ? Config.DEV_URL : Config.PRO_URL;
	config.header = {
		'Content-Type': 'application/json'
	}
	return config
})

// 在请求之前拦截
network.interceptors.request.use((config) => {
	config.header = {
		...config.header,
		't': uni.getStorageSync("token") || "",
	}

	//console.log("req method", config.method)
	// 传递的参数都进行加密
	if (config.data) { //POST
		//console.log("req data", config.data)
		config.header.s = _sign(config.method, config.data, _appKey, _appSecret)
	} else if (config.params) { //GET 
		//console.log("req params", config.params)
		config.header.s = _sign(config.method, config.params, _appKey, _appSecret)
	}
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

//在请求之后拦截
network.interceptors.response.use(async (response) => {
	let dataRes = response.data
	// 服务端返回的状态码不等于200，则reject()
	if (dataRes && dataRes.code === 200) {
		//console.log("success", dataRes)
		return dataRes.data
	}

	// return Promise.reject 可使promise状态进入catch
	return Promise.reject(response)

}, async (response) => {
	console.error("fail:", response)
	//未授权 小程序 自动授权
	// #ifdef MP
	if (response.statusCode === 401) {//token异常
		let {config} = response
		let mp = await Auth.loginCode();
		let res = await network.request({
			url: '/app/v2/auth/mp',
			method: 'POST',
			data: {
				platform: mp.provider,
				code: mp.code
			}
		})
		//获取到token 则缓存刷新
		if (res && res.token) {
			uni.setStorageSync('token', res.token)
			return network.request(config)
		}
	}
	// #endif
	
	return Promise.reject(response)
})

export default network
